package com.binvshe.binvshe.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.binvshe.binvshe.R;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.f2prateek.dart.Dart;
import com.f2prateek.dart.InjectExtra;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.dialog.IOSAlertListFragment;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2016/8/3
 * 确认订单界面
 */
public class IndentSureActivity extends BaseActivity {

    private static final String KEY_ORDER_MSG = "ORDER_MSG";
    private static final String KEY_ACTIVITY_ENTITY = "ACTIVITY_ENTITY";
    private static final String KEY_NUM = "ACTIVITY_NUM";
    @Bind(R.id.tvActTitle)
    TextView mTvActTitle;
    @Bind(R.id.tvActTime)
    TextView mTvActTime;
    @Bind(R.id.btnCommit)
    TextView mBtnCommit;
    @Bind(R.id.tvActPlace)
    TextView mTvActPlace;
    @Bind(R.id.tvTickType)
    TextView mTvTickType;
    @Bind(R.id.tvTickPrice)
    TextView mTvTickPrice;
    @Bind(R.id.tvTickNum)
    TextView mTvTickNum;
    @Bind(R.id.tvTotal)
    TextView mTvTotal;

    private String orderNo;
    private PayReceiver payReceiver;
    private int num;

    @InjectExtra(KEY_ORDER_MSG)
    OrderEntity mOrderMsg;
    @InjectExtra(KEY_ACTIVITY_ENTITY)
    TicketSelectEntity mTicketSelectEntity;


    AlertDialogFragment tipDialog = new AlertDialogFragment();
    private IOSAlertListFragment dialogSelectPay = new IOSAlertListFragment();


    private PayTask alipay;
    private IWXAPI msgApi;
    private String userID;

    @Override
    protected void onResume() {
        super.onResume();
//        dismissLoadingDialog();
    }

    @Override
    protected void onDestroy() {
        if (payReceiver != null) {
            unregisterReceiver(payReceiver);
        }
        super.onDestroy();
    }

    public static void start(Context context, OrderEntity orderMsg, TicketSelectEntity ticketSelectEntity,int num) {
        Intent starter = new Intent(context, IndentSureActivity.class);
        starter.putExtra(KEY_ORDER_MSG, orderMsg);
        starter.putExtra(KEY_ACTIVITY_ENTITY, ticketSelectEntity);
        starter.putExtra(KEY_NUM, num);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTitle();
        initView();
        initDialog();
        initData();
    }

    private void initTitle() {
        getCustomToolbar().addLeftImageButton(R.drawable.top_back, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tipDialog.show(getSupportFragmentManager());
            }
        });
        getCustomToolbar().setTitle("订单确认");
    }

    private void initDialog() {
        tipDialog.setMessage("是否取消订单");
        tipDialog.setPositiveButton("是", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelOrder();
            }
        });
        tipDialog.setNegativeButton("继续购买", true, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tipDialog.dismiss();
            }
        });
        List<String> list = new ArrayList<>();
        list.add("支付宝支付");
        list.add("微信支付");
        dialogSelectPay.setActionList(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        getalipayInfo();
                        break;
                    case 1:
                        wechatPayInfo();
                        break;

                }
            }
        }, list);
    }

    public void initView() {
        ButterKnife.bind(this);
        Dart.inject(this);
        num = getIntent().getIntExtra(KEY_NUM, 0);
        msgApi = WXAPIFactory.createWXAPI(this, null);
        // 将该app注册到微信
        msgApi.registerApp(Constants.WETHAR_APPID);
        alipay = new PayTask(this);
        payReceiver = new PayReceiver();
        registerReceiver(payReceiver, new IntentFilter(Constants.INTENT_BROAD.WECHAR_PAY));
    }


    public void initData() {
        String title = mTicketSelectEntity.getActivity().getName();
        String place = getString(R.string.sure_indent_addr, mTicketSelectEntity.getActivity().getAddress());
        String time = dateForString(mTicketSelectEntity.getActivity().getBegin_time());
        String toTime = dateForString(mTicketSelectEntity.getActivity().getEnd_time(), 0);
        String tickName = mOrderMsg.getName();
        String tickPrice = getString(R.string.ticket_price, mTicketSelectEntity.getPrice() + "");
        String tickNum = (mOrderMsg.getTotal_price() / mTicketSelectEntity.getPrice()) + "";
        double total = mOrderMsg.getTotal_price();

        mTvActTitle.setText(title);
        mTvActTime.setText(Html.fromHtml(getString(R.string.sure_indent_time, time + " - " + toTime)));
        mTvActPlace.setText(Html.fromHtml(place));
        mTvTickType.setText(tickName);
        mTvTickPrice.setText(total/num+"");
        mTvTickNum.setText(num+"");
        mTvTotal.setText(getString(R.string.ticket_price, total + ""));
//        initBuyDialog();
    }


    @OnClick({R.id.btnCommit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnCommit:
                dialogSelectPay.show(getSupportFragmentManager(), "");
                break;
        }
    }

    public String dateForString(long dateMill) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String date = sdf.format(new Date(dateMill));
        return date;
    }

    public String dateForString(long dateMill, int i) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
        String date = sdf.format(new Date(dateMill));
        return date;
    }



    private AlipayHanlder alipayHanlder = new AlipayHanlder();


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            tipDialog.show(getSupportFragmentManager());
        }

        return false;
    }


    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_sure_indent, container, false);
    }

    private class AlipayHanlder extends Handler {
        @Override
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((String) msg.obj);
            String resultStatus = payResult.getResultStatus();
            String result = payResult.getResult();
            if (TextUtils.equals(resultStatus, "9000")) {
//                Toast.makeText(IndentSureActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                Log.d("kyluzoi", "支付成功");
                PaySuccessActivity.start(IndentSureActivity.this, mOrderMsg);
                IndentSureActivity.this.finish();

            } else {
                // 判断resultStatus 为非“9000”则代表可能支付失败
                // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                if (TextUtils.equals(resultStatus, "8000")) {
                    Toast.makeText(IndentSureActivity.this, "支付结果确认中",
                            Toast.LENGTH_SHORT).show();

                } else {
                    // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                    Toast.makeText(IndentSureActivity.this, "支付失败",
                            Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 调用阿里支付
     */
    public void startAliPay(final AliPayInfo info) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                // 调用支付接口，获取支付结果
                String result = alipay.pay(info.getOrderString());
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                alipayHanlder.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 调用微信支付
     * @param wechatPayEntity
     */
    public void onStartWechatPay(WechatPayEntity wechatPayEntity) {
        PayReq request = new PayReq();
            //微信分配的公众账号ID
            request.appId = wechatPayEntity.getAppid();
            //微信支付分配的商户号
            request.partnerId = wechatPayEntity.getPartnerid();
            //微信返回的支付交易会话ID
            request.prepayId = wechatPayEntity.getPrepayid();
            //暂填写固定值Sign=WXPay
            request.packageValue = wechatPayEntity.getPackageX();
            //随机字符串，不长于32位。推荐随机数生成算法
            request.nonceStr = wechatPayEntity.getNoncestr();
            //时间戳，请见接口规则-参数规定
            request.timeStamp = wechatPayEntity.getTimestamp();
            //签名，详见签名生成算法
            request.sign = wechatPayEntity.getSign();
            msgApi.sendReq(request);
    }

    /**
     * 微信成功回调广播
     */
    private class PayReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            PaySuccessActivity.start(IndentSureActivity.this, mOrderMsg);
            IndentSureActivity.this.finish();
        }
    }

    /**
     * 获取支付宝支付信息
     */
    private void getalipayInfo() {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.ALIPAY_INFO, mOrderMsg.getOrder_no());
        request.get(url, new UrlParams(), new DataRequestListener<AliPayInfo>(AliPayInfo.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(AliPayInfo o) {
                startAliPay(o);
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndentSureActivity.this, strMsg, Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    /**
     * 获取微信支付信息
     */
    private void wechatPayInfo() {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.WECHAT_PAYINFO, mOrderMsg.getOrder_no());
        request.get(url, new UrlParams(), new DataRequestListener<WechatPayEntity>(WechatPayEntity.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(WechatPayEntity o) {
                onStartWechatPay(o);
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndentSureActivity.this, strMsg, Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }
    /**
     * 取消订单
     */
    private void cancelOrder() {
        IHttpRequest request = new MyHttpRequest(this);
        String url = String.format(UrlCenter.CANCEL_ORDER, mOrderMsg.getOrder_no());
        request.delete(url, new UrlParams(), new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(String o) {
                finish();
                super.onSuccess(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndentSureActivity.this, strMsg, Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

}
